/**
 * 支付管理-订单退款查询
 */
var orderRefundsMask = new Ext.LoadMask(Ext.getBody(), {
			msg : "正在提交,请稍后..."
		});
var queryOrderRefundsSearch = function() {
	var queryOrderRefundsFieldSet = new Ext.form.FieldSet({
				id : 'queryOrderRefundsFieldSet',
				title : '查询条件',
				collapsible : true,// 可折叠
				buttonAlign : 'center',
				keys : [{
							key : 13, // 13代表回车
							fn : queryRefunds,
							scope : this
						}],
				items : [{
					layout : 'column',
					border : false,
					items : [{
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
											xtype : 'localcommonbox',
											anchor : '100%',
											fieldLabel : '退款状态',
											hiddenName : 'refundsStatus',
											loaclarr : [['0', '待退款']],
											value : 0
										}]
							}, {
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
									layout : 'column',
									border : false,
									items : [{
												text : '查询',
												xtype : 'button',
												width : 80,
												handler : function() {
													queryRefunds();
												},
												style : {
													marginLeft : "100px",
													marginRight : "10px"
												}
											}, {
												text : '重置',
												xtype : 'button',
												width : 80,
												handler : function() {
													Ext
															.getCmp('queryOrderRefundsForm')
															.getForm().reset();
												}
											}]
								}]
							}]
				}]
			});
	fieldSetListeners(['queryOrderRefundsFieldSet', 'queryOrderRefundsForm',
					'orderRefundsManagerGrid'], [0.12, 0.88]);

	var queryOrderRefundsForm = new Ext.form.FormPanel({
				id : 'queryOrderRefundsForm',
				anchor : '100% 12%',
				frame : true,
				labelAlign : 'right',
				bodyBorder : false,
				items : [queryOrderRefundsFieldSet]
			});
	return queryOrderRefundsForm;
};

/**
 * grids
 */
var orderRefundsManagerGrid = function() {
	var orderRefundsManagerSm = new Ext.grid.CheckboxSelectionModel;
	// 创建选择模式对象
	// 定义表的每列（对应表头信息）
	var orderRefundsManagerCm = new Ext.grid.ColumnModel([
			orderRefundsManagerSm, new Ext.grid.RowNumberer(), {
				dataIndex : "id",
				header : "退款编号",
				width : 60
			}, {
				dataIndex : "orderId",
				header : "订单编号",
				width : 60
			}, {
				dataIndex : "orderCode",
				header : "订单编码",
				sortable : true,
				width : 160,
				renderer : function(value, cellmeta, record, rowIndex,
						columnIndex, store) {
					var returnValue = "";
					var orderId = record.data.orderId;
					if (value) {
						returnValue = '<a href ="#" onClick="refundsLookOrderDetail(\''
								+ orderId + '\')">' + value + '</a>';
					}
					return returnValue;
				}
			}, {
				dataIndex : "beforeRefundOrderStatus",
				header : "退款前订单状态",
				sortable : true,
				width : 100,
				renderer : function(value) {
					return '<div style="color:red;">'
							+ PmsUtil.OrderStatus(value) + '</div>';
				}
			}, {
				dataIndex : "refundsPrice",
				header : "退款金额",
				sortable : true,
				width : 60,
				renderer : function(value) {
					return PmsUtil.Price(value);
				}
			}, {
				dataIndex : "refundsReason",
				header : "退款原因",
				sortable : true,
				width : 140,
				renderer : function(value, meta, record) {
					if (value) {
						meta.attr = 'ext:qtitle="退款原因:" ext:qtip="' + value
								+ '"';
						return value;
					}
				}
			}, {
				dataIndex : "refundsStatus",
				header : "退款状态",
				sortable : true,
				width : 80,
				renderer : function(value) {
					return '<div style="color:red;">'
							+ PmsUtil.OrderRefundsStatus(value) + '</div>';
				}
			}, {
				dataIndex : "createdName",
				header : "创建人",
				sortable : false,
				width : 70
			}, {
				dataIndex : "createdDate",
				header : "创建时间",
				sortable : false,
				width : 130
			}, {
				header : "管理",
				width : 120,
				dataIndex : "orderId",
				sortable : false,
				renderer : function(j, i, g, m, h) {
					var id = g.data.id;
					var orderId = g.data.orderId;
					var refundsStatus = g.data.refundsStatus;
					var orderStatusArr = g.data.beforeRefundOrderStatus;
					var k = "";
					if (isGranted("orderRefundsManager_退款中")) {
						if (refundsStatus == 0) {
							k += '&nbsp;&nbsp;<a href="#" onclick="orderRefundStatusOne('
									+ id
									+ ','
									+ "1"
									+ ','
									+ "'退款中'"
									+ ')\">退款审核</a>';
						}
					}
					if (isGranted("orderRefundsManager_拒绝")) {
						if (refundsStatus == 0) {
							k += '&nbsp;&nbsp;<a href="#" onclick="orderRefundStatusRefuseOne('
									+ id
									+ ','
									+ "3"
									+ ','
									+ orderStatusArr
									+ ',' + "'拒绝退款'" + ')\">拒绝</a>';
						}
					}
					return k;
				}
			}]);

	// 定义分析器
	var orderRefundsManagerReader = new Ext.data.JsonReader({
				totalProperty : "totalCount",
				root : "list",
				fields : [{
							name : "id"
						}, {
							name : "orderId"
						}, {
							name : "orderCode"
						}, {
							name : "refundsReason"
						}, {
							name : "refundsPrice"
						}, {
							name : "refundsStatus"
						}, {
							name : "refusedReason"
						}, {
							name : "beforeRefundOrderStatus"
						}, {
							name : "createdName"
						}, {
							name : "createdDate"
						}]
			});

	// 取数据store
	var orderRefundsViewStore = new Ext.data.Store({
				autoLoad : true,// 要加载数据必须设置为true
				proxy : new Ext.data.HttpProxy({
							url : __ctxPath
									+ "/orderManager/selectOrderRefunds"
						}),
				remoteSort : false,
				baseParams : {
					start : 0,
					limit : 25
				},
				listeners : {
					beforeload : {
						fn : function(thiz, options) {
							Ext.apply(thiz.baseParams, Ext
											.getCmp('queryOrderRefundsForm')
											.getForm().getValues());
						}
					}
				},
				reader : orderRefundsManagerReader
			});

	// 定义grid的toolbar
	var orderRefundsTb = new Ext.Toolbar({
				id : "orderRefundsTb",
				height : 25,
				items : []
			});
	orderRefundsTb.add(new Ext.scm.Button({
				text : "批量审核",
				width : 80,
				pressed : true,
				hsValue : 'orderRefundsManager_批量退款中',
				iconCls : "btn-edit",
				listeners : {
					"click" : function() {
						batchOrderUpdateRefundsStatus(1, '退款中');
					}
				}
			}));

	orderRefundsTb.add(new Ext.Toolbar.Spacer());
	orderRefundsTb.add(new Ext.scm.Button({
				text : "批量拒绝",
				width : 80,
				pressed : true,
				hsValue : 'orderRefundsManager_批量拒绝',
				iconCls : "btn-edit",
				listeners : {
					"click" : function() {
						batchOrderRefundsStatus(3, '拒绝退款');
					}
				}
			}));
	orderRefundsTb.add(new Ext.Toolbar.Spacer());
	orderRefundsTb.add(new Ext.scm.Button({
				text : "刷 新",
				iconCls : "btn-refresh",
				width : 80,
				hsValue : 'orderRefundsManager_刷新',
				pressed : true,
				handler : function() {
					queryRefunds();
				}
			}));

	var orderRefundsManagerGrid = new Ext.grid.GridPanel({
				id : 'orderRefundsManagerGrid',
				store : orderRefundsViewStore,
				cm : orderRefundsManagerCm,
				sm : orderRefundsManagerSm,
				autoScroll : true,
				loadMask : true,
				stripeRows : true,
				columnLines : true,
				loadMask : {
					msg : "正在加载数据，请稍侯……"
				},
				viewConfig : {
					emptyText : '没有您想要的数据!',
					forceFit : true,
					scrollOffset : 0
				},
				anchor : '100% 88%',
				frame : true,
				tbar : orderRefundsTb,
				bbar : new PG.PagingBar({
							store : orderRefundsViewStore
						})
			});
	return orderRefundsManagerGrid;
};

// 查询
function queryRefunds() {
	var grid = Ext.getCmp("orderRefundsManagerGrid");
	var form = Ext.getCmp("queryOrderRefundsForm");
	if (form.getForm().isValid()) {
		grid.getStore().load();
	}
}

// 单个退款 改变订单状态
function orderRefundStatusOne(id, refundsStatus, statusName) {
	Ext.Msg.confirm("信息确认", "您确定要将订单状态变更为<span style='color:#F00'>"
					+ statusName + "</span>？", function(c) {
				if (c == "yes") {
					updRefundOrderStatus(id, refundsStatus, statusName);
				}
			});
}

// 退款操作
function updRefundOrderStatus(ids, refundsStatus, statusName) {
	orderRefundsMask.show();
	Ext.Ajax.request({
				url : __ctxPath + "/orderManager/updateOrderRefundsStatus",
				params : {
					ids : ids,
					refundsStatus : refundsStatus,
					statusName : statusName
				},
				method : "post",
				success : function(response, config) {
					orderRefundsMask.hide();
					var jsonData = Ext.util.JSON.decode(response.responseText);
					if (jsonData.success) {
						Ext.MessageBox.show({
									title : "信息提示",
									msg : jsonData.data,
									buttons : Ext.MessageBox.OK,
									icon : Ext.MessageBox.INFO
								});
						queryRefunds();
					} else {
						Ext.MessageBox.show({
									title : "操作信息",
									msg : jsonData.data,
									buttons : Ext.MessageBox.OK,
									icon : Ext.MessageBox.ERROR
								});
					}
				},
				failure : function(response, config) {
					orderRefundsMask.hide();
					Ext.MessageBox.show({
								title : "错误提示",
								msg : "服务器请求异常，请稍后再试!",
								buttons : Ext.MessageBox.OK,
								icon : Ext.MessageBox.ERROR
							});
				}
			});
}

// 批量退款
function batchOrderUpdateRefundsStatus(refundsStatus, statusName) {
	var d = Ext.getCmp("orderRefundsManagerGrid");
	var jsonrecord = d.getSelectionModel().getSelections();
	if (jsonrecord.length == 0) {
		Ext.MessageBox.show({
					title : "操作信息",
					msg : "请选择要退款的订单!",
					buttons : Ext.MessageBox.OK,
					icon : Ext.MessageBox.WARNING
				});
		return;
	}
	Ext.Msg.confirm("信息确认", "您确定要将订单状态变更为<span style='color:#F00'>"
					+ statusName + "</span>？", function(c) {
				if (c == "yes") {
					var ids = "";
					var m = 0;
					console.info(jsonrecord);
					for (var i = 0; i < jsonrecord.length; i++) {
						var tmp = jsonrecord[i];
						console.log(tmp.data.refundsStatus)
						if (refundsStatus - tmp.data.refundsStatus != 1) {
							if (refundsStatus == tmp.data.refundsStatus) {
								Ext.MessageBox.show({
											title : "提示信息",
											msg : "您选择的订单编号为<span style='color:#F00'>"
													+ tmp.data.orderId
													+ "</span>的订单已经是"
													+ statusName + "!",
											buttons : Ext.MessageBox.OK,
											icon : Ext.MessageBox.WARNING
										});
								return;
							} else if (tmp.data.refundsStatus == 2
									|| tmp.data.refundsStatus == 3) {
								Ext.MessageBox.show({
											title : "提示信息",
											msg : "您选择的订单编号为<span style='color:#F00'>"
													+ tmp.data.orderId
													+ "</span>的订单状态不能直接改为"
													+ statusName + "!",
											buttons : Ext.MessageBox.OK,
											icon : Ext.MessageBox.WARNING
										});
								return;
							}

						}
						if (m > 0) {
							ids = ids + "," + tmp.data.id;
						} else {
							ids = tmp.data.id;
						}
						m++;
					}
					updRefundOrderStatus(ids, refundsStatus, statusName);
				}
			});
}

// 批量拒绝退款
function batchOrderRefundsStatus(refundsStatus, statusName) {
	var d = Ext.getCmp("orderRefundsManagerGrid");
	var jsonrecord = d.getSelectionModel().getSelections();
	if (jsonrecord.length == 0) {
		Ext.MessageBox.show({
					title : "操作信息",
					msg : "请选择拒绝退款订单!",
					buttons : Ext.MessageBox.OK,
					icon : Ext.MessageBox.WARNING
				});
		return;
	}
	Ext.Msg.confirm("信息确认", "您确定要将订单状态变更为<span style='color:#F00'>"
					+ statusName + "</span>？", function(c) {
				if (c == "yes") {
					var ids = "";
					var m = 0;
					console.info(jsonrecord);
					for (var i = 0; i < jsonrecord.length; i++) {
						var tmp = jsonrecord[i];
						if (refundsStatus - tmp.data.refundsStatus != 1) {
							if (refundsStatus == tmp.data.refundsStatus) {
								Ext.MessageBox.show({
											title : "提示信息",
											msg : "您选择的订单编号为<span style='color:#F00'>"
													+ tmp.data.orderId
													+ "</span>的订单已经是"
													+ statusName + "!",
											buttons : Ext.MessageBox.OK,
											icon : Ext.MessageBox.WARNING
										});
								return;
							} else if (tmp.data.refundsStatus == 1
									|| tmp.data.refundsStatus == 2) {
								Ext.MessageBox.show({
											title : "提示信息",
											msg : "您选择的订单编号为<span style='color:#F00'>"
													+ tmp.data.orderId
													+ "</span>的订单状态不能直接改为"
													+ statusName + "!",
											buttons : Ext.MessageBox.OK,
											icon : Ext.MessageBox.WARNING
										});
								return;
							}

						}
						if (m > 0) {
							ids = ids + "," + tmp.data.id;
						} else {
							ids = tmp.data.id;
							orderStatusArr = tmp.data.beforeRefundOrderStatus;
						}
						m++;
					}
					orderRefundStatusRefuseOne(ids, refundsStatus,
							orderStatusArr, statusName);
				}
			});
}
// 拒绝退款
function orderRefundStatusRefuseOne(ids, refundsStatus, orderStatusArr,
		statusName) {
	orderRefundsStatusRemarkWindows(ids, refundsStatus, orderStatusArr,
			statusName).show();
}

function orderRefundsStatusRemarkWindows(ids, refundsStatus, orderStatusArr,
		statusName) {
	var orderRefundsForm = new Ext.FormPanel({
				id : "orderRefundsForm",
				frame : true,
				bodyBorder : false,
				anchor : '100% 100%',
				items : [{
							name : "id",
							xtype : "hidden",
							value : ids
						}, {
							xtype : "textarea",
							fieldLabel : "拒绝退款原因",
							name : "refusedReason",
							vtype : "validateMaxLength",
							confirmTo : 500,
							anchor : '100%',
							height : 120
						}]
			});
	var orderRefundsManagerWindow = new Ext.Window({
		id : "orderRefundsManagerWindow",
		title : "拒绝退款",
		width : 400,
		height : 220,
		closable : true,
		modal : true,
		layout : "fit",
		autoDestroy : true,
		plain : true,
		buttonAlign : "center",
		items : orderRefundsForm,
		buttons : [{
			text : "保存",
			width : 60,
			handler : function() {
				var uploadForm = orderRefundsForm.getForm();
				if (uploadForm.isValid()) {
					Ext.Msg.confirm("信息确认", "确认要拒绝退款吗？", function(c) {
						if (c == "yes") {
							uploadForm.submit({
								url : __ctxPath
										+ "/orderManager/updateOrderRefundsStatus",
								params : {
									ids : ids,
									refundsStatus : refundsStatus,
									orderStatusArr : orderStatusArr,
									statusName : statusName
								},
								method : "post",
								waitTitle : "请稍后",
								waitMsg : "正在提交数据...",
								success : function(response, options) {
									queryRefunds();
									orderRefundsManagerWindow.close();
									var jsonData = Ext.util.JSON
											.decode(options.response.responseText);
									Ext.MessageBox.show({
												title : "信息提示",
												msg : jsonData.data,
												buttons : Ext.MessageBox.OK,
												icon : Ext.MessageBox.INFO
											});
								},
								failure : function(response, options) {
									var jsonData = Ext.util.JSON
											.decode(options.response.responseText);
									Ext.MessageBox.show({
												title : "操作信息",
												msg : jsonData.data,
												buttons : Ext.MessageBox.OK,
												icon : Ext.MessageBox.ERROR
											});
									orderRefundsManagerWindow.close();
								}
							});
						}
					})
				}
			}
		}, {
			text : "重置",
			width : 60,
			handler : function() {
				orderRefundsForm.form.reset();
			}
		}, {
			text : "取消",
			width : 60,
			handler : function() {
				orderRefundsManagerWindow.close();
			}
		}]
	});
	return orderRefundsManagerWindow;
}

/**
 * 查询订单详情
 * 
 * @param {}
 *            id
 */
function refundsLookOrderDetail(id) {
	var centerPanel = App.getContentPanel();
	var tab = centerPanel.getItem(PmsUtil.ORDER_MESSAGE_DETAIL);
	var createNewTab = new CreatNewTab(PmsUtil.ORDER_MESSAGE_DETAIL, '订单详情');
	if (tab == null) {
		createNewTab.createNew(tab);
	} else {
		createNewTab.createOld(tab, ['lookOrderDetailFields',
						'lookOrderDetailForm', 'lookOrderDetailGrid']);
	}
	Ext.Loader.load([__ctxPath + '/js/order/orderDetail.js'], function() {
				Ext.getCmp("centerTabPanel").getActiveTab().add(
						lookOrderDetailSearch(id), orderDetailGrid(id));
				Ext.getCmp("centerTabPanel").getActiveTab().doLayout();
			});
}

Ext.getCmp("centerTabPanel").getActiveTab().add(queryOrderRefundsSearch(),
		orderRefundsManagerGrid());
Ext.getCmp("centerTabPanel").getActiveTab().doLayout();
